package com.cold.demo.template.test;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 知苗预约
 */
public class GrabHPVForXFInZMYY {

    public static final Logger log = LoggerFactory.getLogger(GrabHPVForXFInZMYY.class.getSimpleName());

    private static volatile Map<String, List<String>> headers;

    static {
        generateHeader();
    }

    private static Map<String, List<String>> generateHeader() {
        if (headers != null) {
            return headers;
        }
        String sql = "Host: cloud.cn2030.com\n" +
                "Connection: keep-alive\n" +
                "Cookie: ASP.NET_SessionId=ldmu1l2mpy4irgpbzy4jq0o5\n" +
                "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat\n" +
                "content-type: application/json\n" +
                "zftsl: 4487121344aa662e1fe35fee33c0a9f3\n" +
                "Referer: https://servicewechat.com/wx2c7f0f3c30d99445/86/page-frame.html\n" +
                "Accept-Encoding: gzip, deflate, br";

        String[] split = sql.split("\n");
        Map<String, List<String>> res = new HashMap<>();
        for (String s : split) {
            String sp = ": ";
            String key = s.split(sp)[0];
            String value = s.replace(key + sp, "");
            List<String> list = res.computeIfAbsent(key, k -> new ArrayList<>());
            list.add(value);
        }
        headers = res;
        return headers;
    }


    public static void main(String[] args) throws InterruptedException {
        generateHeader();

        query();

    }

    private static void query() {
        /*
act=CustomerList
city=["","",""]
lat=39.90469
lng=116.40717
id=4
cityCode=0
product=1
         */
        Map<String, Object> param = new HashMap<>();
        param.put("act", "CustomerList");
        param.put("lat", 39.90469);
        param.put("lng", 116.40717);
        param.put("product", 1);// 九价

        /*param.put("city", "[\"四川省\",\"成都市\",\"\"]");
        param.put("id", 0);
        param.put("cityCode", 510100);// 四川省成都市的代码*/
        param.put("city", "[\"四川省\",\"成都市\",\"\"]");
        param.put("id", 4);
        param.put("cityCode", 0);

        String url = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx";

        HttpRequest get = HttpUtil.createGet(url);
        get.form(param);
        get.header(headers);
        String body = get.execute().body();

        JSONObject jsonObject = JSONObject.parseObject(body);
        if (jsonObject.getIntValue("status") == 200) {
            // success
            JSONArray list = jsonObject.getJSONArray("list");
            log.info("医院的数量有：{}", list.size());
            for (Object o : list) {
                JSONObject j = (JSONObject) o;
                String cname = j.getString("cname");
                List<String> tags = j.getJSONArray("tags") == null ? new ArrayList<>() : j.getJSONArray("tags").toJavaList(String.class);
                if (tags.contains("可预约") || true) {
                    log.info("可预约的医院：{}", cname);
                    if (cname.contains("重庆万家燕医院")) {
                        // 查询医院的各种疫苗是否存在可以预约的疫苗
                        queryHPV("CustomerProduct", j.getString("id"), j.getBigDecimal("lat"), j.getBigDecimal("lng"));
                    }
                }
            }
        } else {
            // fail
            log.error("请求失败，响应值{}", body);
        }
    }

    @Test
    public void test4()throws Exception{
        queryHPV("CustomerProduct","2562",BigDecimal.valueOf(39.90469)
                ,BigDecimal.valueOf(116.40717));
    }

    private static void queryHPV(String act, String id, BigDecimal lat, BigDecimal lng) {
        String url = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx";
        Map<String, Object> param = new HashMap<>();
        param.put("act", act);
        param.put("id", id);
        param.put("lat", lat);
        param.put("lng", lng);
        HttpRequest get = HttpUtil.createGet(url);
        get.form(param);
        get.header(headers);
        String body = get.execute().body();
        JSONObject result = JSONObject.parseObject(body);
        JSONArray list = result.getJSONArray("list");
        if (CollectionUtils.isEmpty(list)) return;
        for (Object o : list) {
            JSONObject j = (JSONObject) o;
            // 先将这里注释掉，只捕获九价疫苗
            boolean time = false;
            String[] dates = null;
            LocalDateTime sDate = null, eDate = null;
            try {
                dates = j.getString("date").split(" 至 ");
                sDate = DateUtil.parseLocalDateTime(Year.now().getValue() + "-" + dates[0] + ":00");
                eDate = DateUtil.parseLocalDateTime(Year.now().getValue() + "-" + dates[1] + ":00");
                if (sDate.getDayOfYear() <= LocalDateTime.now().getDayOfYear() && LocalDateTime.now().getDayOfYear() <= eDate.getDayOfYear()) {
                    time = true;
                }
            } catch (Exception ignored) {
            }
            String text = j.getString("text");
            if (/*"true".equals(j.getString("enable")) && */ time && (text.contains("九价人") || text.contains("四价人"))) {
                log.info("\t\t可以预约的疫苗：{}\t{}({})", j.getString("date"), text, result.getString("cname"));
                queryHPVDate("GetCustSubscribeDateAll", j.getString("id"), id, DateUtil.format(new Date(), "yyyyMM"));// https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?
            }
        }

    }

    @Test
    public void test5()throws Exception{
        String res = queryHPVDate2("GetCustSubscribeDateAll", "1", "2562", "202110");
        System.out.println(res);
    }

    private static String queryHPVDate2(String act, String pid, String id, String month) {
        String url = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx";
        HttpRequest get = HttpUtil.createGet(url);
        Map<String, Object> param = new HashMap<>();
        param.put("act", act);
        param.put("pid", pid);
        param.put("id", id);
        param.put("month", month);
        get.header(headers, true);
        get.form(param);
        // {"status":200,"list":[{"date":"2021-10-11","enable":true}]}
        String body = get.execute().body();
        return body;
    }
    private static void queryHPVDate(String act, String pid, String id, String month) {
        String url = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx";
//        https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx?act=GetCustSubscribeDateAll&pid=1&id=2561&month=202110
        HttpRequest get = HttpUtil.createGet(url);
        Map<String, Object> param = new HashMap<>();
        param.put("act", act);
        param.put("pid", pid);
        param.put("id", id);
        param.put("month", month);
        get.header(headers, true);
        get.form(param);
        // {"status":200,"list":[{"date":"2021-10-11","enable":true}]}
        String body = get.execute().body();
        System.out.println(body);
//        body = "{\"status\":200,\"list\":[{\"date\":\"2021-10-18\",\"enable\":true}]}";
        JSONObject jsonObject = JSONObject.parseObject(body);
        JSONArray list = jsonObject.getJSONArray("list");
        if (CollectionUtils.isEmpty(list)) return;
        for (Object o : list) {
            JSONObject j = (JSONObject) o;
            String date = j.getString("date");
            queryHPVDateSingle("GetCustSubscribeDateDetail", pid, id, date);
        }
    }

    public static void queryHPVDateSingle(String act, String pid, String id, String sc_date) {
        String url = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx";
        HttpRequest get = HttpUtil.createGet(url);
        Map<String, Object> param = new HashMap<>();
        param.put("act", act);
        param.put("pid", pid);
        param.put("id", id);
        param.put("scdate", sc_date);
        System.out.println(JSONObject.toJSONString(param));
        get.header(headers, true);
        get.form(param);
        String body = get.execute().body();
        log.info("\t\t请求最后的某一天的返回值：{}", body);
    }

    @Test
    public void test1() throws Exception {
        String url = "https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx";
        HttpRequest get = HttpUtil.createGet(url);
        // {"scdate":"2021-10-18","act":"GetCustSubscribeDateDetail","pid":"1","id":"71"}
        // {"scdate":"2021-10-18","act":"GetCustSubscribeDateDetail","pid":"2","id":"71"}
        JSONObject.parseObject("{\"scdate\":\"2021-10-18\",\"act\":\"GetCustSubscribeDateDetail\",\"pid\":\"1\",\"id\":\"71\"}");// 九价
        JSONObject.parseObject("{\"scdate\":\"2021-10-18\",\"act\":\"GetCustSubscribeDateDetail\",\"pid\":\"2\",\"id\":\"71\"}");// 四价
        Map<String, Object> param = new HashMap<>();
        param.put("act", "GetCustSubscribeDateDetail");
        param.put("pid", "1");
        param.put("id", "71");// 2562
        param.put("scdate", "2021-10-12");
        get.header(headers, true);
        get.form(param);
        String body = get.execute().body();
        log.info("\t\t请求最后的某一天的返回值：{}", body);
        // 0C90EACF5FDB51DAD145B406F46E44C5C46CA3C2A6EF1376AC1778788B5FE0AFE86ED56825CD6D7D73DB49218213D41A59446B2FEF01B9CBCE034057C70B03D83314C0C440B0D6A194CF889336D9C6AD7054F4F56D083B3CFF057F583CB171827B34A883AA329319F3D85824C8AF6F94803188CB5BECE58C0D01ABF7499BE5A90F208817AD144443EB9A28B206020DFC03419C5DB8DFF3D4F7E21033E409A6193D9E833FE672522B186C34C122B5654312E93F8CF774F63600B086128A169DBC1713B4D626621BDB369DC2206FC6A71362D2F564348AA208D0A463EDC6CCEE9E0BD1F946E4B15C194BAC7EB68157A897AC86F1FA8CD54ADD2DD5ADCD789024AB596C2F5380F51DC451E1A995450653494E153ABBD9DAA87B0D8C59698CC3DEAD
    }

    @Test
    public void test2() throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("act", "GetCaptcha");
        param.put("mxid", "4m_FAPGLAACkZTQB");
        //4m_FA{CaH}AA{BV}ZTQB
        //4m_FA{PGL}AA{Ck}ZTQB   11-08
        //4m_FA{PGL}AA{Cl}ZTQB   11-09
        HttpRequest get = HttpUtil.createGet("https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx");
        get.header(headers, true);
        get.form(param);
        String body = get.execute().body();
        System.out.println(body);
    }
    /*
九 2021-11-08   4m_FA{PGL}AA{Ck}ZTQB   0BACF17498C9A4ACD8F6E1B60DACC467109EF5806DA3D1B83CDDBFE031EA56293FD4BFB4A127632AE92595400856FB1983A00F0A794CBE14F4F27B4693FE6385FE78A9B8B64C07744104ED3AB18B34C556B8E166A8268235F2CBC49B7DB50849D2BB60C9032A48774139967B5886A903D83578F916B8E4E3BB6E007DE1D4B6C1A10D07B02F024E61AC397231D0828E67B3E39BD79E426F7A65DB3A6D056471B13A3169921A7ECFCA915BB67EEFFA62C4700C830FA14A70527F80691DE35DC63A951426546BC4BF057CA2FF27B758AF4F73B7F3C27CFE5669700A580B501F5395CA48D97D4587987BFA930C364AF607C363A42D920CE0BAC090566A4DFD189FE5417E5B9D00B90432AF8AF25D881FEA16961636B75DD67617BD5DA9CCF52F356E77FC438804A1C84EF045733C4856042A13326DA573A9A454547161C749ADCE16FED56E742DA4453B5B07A32385DA822EC33FBB5F1B3082FD27BBC4D1E34B266039326F86C80FA86763CBC888F91A7D69CF2B64DAEE6EBA045EA8A8814FFFFBF7 D9C489C1185F94E919532334B1AE2A8713B233E543A2894EED23CB871CC7FE21E56C8A573055A9296D078A3A941A0EF8
九 2021-11-09   4m_FA{PGL}AA{Cl}ZTQB   0BACF17498C9A4ACD8F6E1B60DACC467109EF5806DA3D1B83CDDBFE031EA56293FD4BFB4A127632AE92595400856FB1983A00F0A794CBE14F4F27B4693FE6385FE78A9B8B64C07744104ED3AB18B34C556B8E166A8268235F2CBC49B7DB50849D2BB60C9032A48774139967B5886A903D83578F916B8E4E3BB6E007DE1D4B6C1A10D07B02F024E61AC397231D0828E67B3E39BD79E426F7A65DB3A6D056471B13A3169921A7ECFCA915BB67EEFFA62C4700C830FA14A70527F80691DE35DC63A951426546BC4BF057CA2FF27B758AF4F73B7F3C27CFE5669700A580B501F5395CA48D97D4587987BFA930C364AF607C363A42D920CE0BAC090566A4DFD189FE5417E5B9D00B90432AF8AF25D881FEA16961636B75DD67617BD5DA9CCF52F356E77FC438804A1C84EF045733C4856042A13326DA573A9A454547161C749ADCE16FED56E742DA4453B5B07A32385DA822EC33FBB5F1B3082FD27BBC4D1E34B266039326F86C80FA86763CBC888F91A7D69CF2B64DAEE6EBA045EA8A8814FFFFBF7 17DD5EAF247BACBADDAE0776659CCEAC32816910F6313D3FB3906F3889775058F3FA6DB423E45CB531F915A1CDFBBF0D
     */
    @Test
    public void test3()throws Exception{
        // 查询密钥
        HttpRequest get = HttpUtil.createGet("https://cloud.cn2030.com/sc/wx/HandlerSubscribe.ashx");
        Map<String,Object> params = new HashMap<>();
        params.put("act","GetCustSubscribeDateDetail");
        params.put("pid","2");// 1 九价   2 四价
        params.put("id","71");// 医院
        params.put("scdate","2021-11-08");
        get.form(params);
        get.header(headers);
        String body = get.execute().body();
        System.out.println(body);
    }
}
